<?php
include ('common/constants.php');
include ('common/db.php');
session_start();

if ((!isset($_SESSION['user_email'])) || ($_SESSION['user_email']=='')) {
  header('location: login.php');
}

function ifMale($email){
  $sql = "SELECT gender FROM `user` where email='" . $email . "';";
  if($result = mysql_query($sql)){
    if(mysql_result($result, 0) =="F"){
      return "fe";
    }
  }
}

function getNoOfSeats($advert_id){
  $sql2 = " SELECT count(seat_number) FROM `seat` WHERE seat_status = 'open' AND advert_id='". $advert_id . "';";
  //echo $sql2;
  if($result = mysql_query($sql2)){
    return mysql_result($result, 0);
  }
  //echo mysql_error();
}

function showVehicleType($advert_id){
  $sql2 = " SELECT `vehicle_type_id` FROM `advertisement` WHERE advert_id='". $advert_id . "'; ";
  //echo $sql2;
  if($result = mysql_query($sql2)){
      if (mysql_result($result, 0)=="1"){
        return "car";
      }elseif (mysql_result($result, 0)=="2"){
        return "van";
      }elseif (mysql_result($result, 0)=="3"){
        return "dcab";
      }elseif (mysql_result($result, 0)=="4"){
        return "bus";
      }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Carpooling - Home</title>
  <link href="resources/css/bootstrap.min.css" rel="stylesheet">
  <link href="resources/css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="resources/css/datepicker.css" rel="stylesheet">
  <link href="resources/css/jquery.timepicker.css" rel="stylesheet">
  
  <script type="text/javascript" src="resources/js/jquery.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
  
  <style type="text/css">
    #loading {
      display:none; 
      position:absolute; 
      background:#fff; 
    }
    .cus_row {
    	-moz-box-sizing: border-box;
    	float:left;
    	min-height: 1px;
    	padding-left: 15px;
    	padding-right: 15px;
    	position: relative;
    }
    #img-load { 
      position:absolute; 
    }

  </style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container"> 
    	<a class="btn btn-navbar" style="margin-top: 25px;" data-toggle="collapse" data-target=".nav-collapse">
          <span class="icon-bar"></span> 
          <span class="icon-bar"></span> 
          <span class="icon-bar"></span> 
      	</a> <a class="brand" style="text-align:center;" href="home.php"><img src="resources/icons/share_ride.png" style="max-width:55px; padding-right:15px"/>Carpooling.lk</a>
      <div class="nav-collapse collapse">
        <ul class="nav navbar-nav">
          <li style="text-align:center; float:left">
            <a href="advertise.php"><img src="resources/icons/speaker.png" style="max-width:40px; min-width: 20px;"/><br />Advertise</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="publish.php"><img src="resources/icons/publish.png" style="max-width:40px; min-width: 20px;"/><br />Publish</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="#notifPanel" data-toggle="modal"><img src="resources/icons/notification.png" style="max-width:40px; min-width: 20px;"/><br />Notifications</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="my_posts.php"><img src="resources/icons/my_posts.png" style="max-width:40px; min-width: 20px;"/><br />My Posts</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="user_details.php"><img src="resources/icons/user_details.png" style="max-width:40px; min-width: 20px;"/><br />User Details</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="preferences.php"><img src="resources/icons/preferences.png" style="max-width:40px; min-width: 20px;"/><br />Preferences</a>
          </li>
          
          <li style="text-align:center; float:left">
          	<a class="btn-inverse" data-toggle="collapse" data-target="#srch_panel"><img src="resources/icons/search.png" style="max-width:40px; min-width: 20px;"/><br />							Search</a>
          </li>
          <li style="text-align:center; float:left; line-height: 0px; max-width: 200px;">
            &nbsp;&nbsp;<a class="" data-toggle="collapse"><h4>Hi <?php echo $_SESSION['user_name']?></h4></a><br />
          </li>
          <li style="text-align:center; float:left">
            &nbsp;&nbsp;<a style="padding:20px; margin: 0;" href="login.php">Sign Out</a>
          </li>
        </ul>
      </div>
      
	     <!-- Search Panel -->
  	   <div id="includedSrchPanel" class="cus_row" style="width:100%"></div>

       <div style="width: 100%; clear: both; color: white; ">
       <?php 
		  $slctSql = " SELECT seat_number FROM seat where seat_status='booked'";
          $result = mysql_query($slctSql) or trigger_error(mysql_error());
          $num = mysql_num_rows($result);
          if ($num > 0) {
            echo "More than " . $num . " successful seat bookings up to now and counting...";
          }
       ?>
      </div>
    </div>
  </div>
</div>
<div style="height:100px"></div>
<div class="container">
  
  <?php 

  $sql2 = " SELECT up.origin, up.destination FROM `user_preference` up WHERE up.email='{$_SESSION['user_email']}'";

  if($result    = mysql_query($sql2)){

    $origin       = mysql_result($result, 0, "origin");
    $dest         = mysql_result($result, 0, "destination");
  }
  
  $sql = " SELECT a.*, u.name as username, u.email, (select count(advert_id) from `seat` where seat_status='open' and advert_id=a.advert_id ) ";
  $sql .= " FROM advertisement a, user u  ";
  $sql .= " WHERE a.email = u.email AND a.advert_id in (select advert_id from `seat` where seat_status='open') AND a.email <> '{$_SESSION['user_email']}' AND (a.status IS NULL OR a.status <> 'completed')";
  
  if (isset($_GET['origin']) and $_GET['origin'] != "" and $_GET['origin'] != "0") {
      $sql .= " AND a.origin = '{$_GET['origin']}' ";
  }elseif (isset($_GET['destination']) && $_GET['destination']!="" and $_GET['destination'] != "0") {
      $sql .= " AND a.destination = '{$_GET['destination']}' ";
  }elseif (isset($_GET['srch_date']) && $_GET['srch_date']!="" and $_GET['srch_date'] != "0") {
      $sql .= " AND a.travel_date = '{$_GET['srch_date']}' ";

  }else{
    if(!isset($_GET['srch_all']) && $_GET['srch_all']!="yes"){
      if($origin!=""){
        $sql .= " AND a.origin = '{$origin}' ";
      }
      if($dest!=""){
        $sql .= " AND a.destination = '{$dest}' ";
      }
    }
  }

  if(isset($_GET['sortby']) && $_GET['sortby']=="price"){
      $sql .= " ORDER BY a.price ";
  }

  //echo $sql;
  $result = mysql_query($sql) or trigger_error(mysql_error());
  $num = mysql_num_rows($result);
  $i = 0;
  
  if ($num == 0) {
	echo '<h3>No results were found matching the prefered travel requirements</h3>';
  }

  for ( $i=0; $i < $num; $i++ ){ 
  
  $travelDateFormatted = DateTime::createFromFormat('Y-m-d', mysql_result($result, $i, "a.travel_date"));
  
  ?>
  <div class="row">
    <div class="btn btn-default" style="width:100%">
      <div style="padding-top: 20px; height: 173px;">
       <div class="cus_row user-button" style="width:10%; text-align: left;" usrID="<?php echo mysql_result($result,$i,"email"); ?>"> <img class="img-responsive" src="resources/icons/<?php echo ifMale(mysql_result($result,$i,"a.email")); ?>male_user_icon.png" style="min-width: 40px;"/>
          <div><?php echo mysql_result($result,$i,"username"); ?></div>
        </div>
        <div class="cus_row" style="width:65%;">

          <div id="show-on-map" class="route-button" strRoute="<?php echo str_replace("\\", '', mysql_result($result,$i,"travel_route")); ?>">
          
          	<h3 style="font-style:italic; color:#36C"><?php echo nl2br(mysql_result($result,$i,"origin")); ?> <img class="img-responsive" src="resources/icons/to.png"  style="min-width: 40px;"/> <?php echo nl2br(mysql_result($result,$i,"destination")); ?></h3>[Click to view/edit Route]
          </div>
          <!--
          <div id="div-show-on-map"><button type="button" class="btn" id="show-on-map">[Show Route]</button></div>
          -->
          
          <h4 style="color:#F30"><span id="<?php echo mysql_result($result,$i,"a.advert_id"); ?>"><?php echo getNoOfSeats(mysql_result($result,$i,"a.advert_id")); ?></span> seat(s) <?php if (mysql_result($result,$i,"advertisement_type")=="advert") {
            echo "available";
          } else {
            echo "required";
          }
           ?> </h4>
           <?php if (mysql_result($result, $i, "a.price")!="0") { echo "<h4>Price per Seat-Trip: Rs.".nl2br(mysql_result($result,$i,"price")). "</h4>"; } ?> 
           <?php if (mysql_result($result, $i, "a.travel_date")!="0000-00-00") { echo "<h4>Travel Date : ".$travelDateFormatted->format('Y-m-d')."</h4>"; } ?> 
           <?php if (mysql_result($result, $i, "a.travel_distance")!="0") { echo "Distance (Km) : ".mysql_result($result,$i,"a.travel_distance")." / "; } if (mysql_result($result, $i, "a.travel_time")!="0") { echo "Duration (Hrs) : ".mysql_result($result,$i,"a.travel_time"); }  ?>
          
        </div>
        <div class="cus_row" style="width:15%; text-align: right;"> 
          <img rel="<?php echo mysql_result($result,$i,"seat_number"); ?>" id="<?php echo mysql_result($result,$i,"advert_id"); ?>" class="accept-btn img-responsive" src="resources/icons/<?php if (mysql_result($result,$i,"advertisement_type")=="advert") {
            echo "book_now.png";
          } else {
            echo "accept_icon.png";
          }
           ?>" style="min-width: 120px;"  /> </div>
      </div>
      <div style="padding-top: 30px;">
        <div class="cus_row" style="width:10%; text-align: left;"> <img class="img-responsive" src="resources/icons/<?php echo showVehicleType(mysql_result($result,$i,"a.advert_id")); ?>_icon.png"  style="min-width: 40px;"/> </div>
        <div class="cus_row" style="width:65%;">
          <p>
            <?php 
              if (mysql_result($result,$i,"split_cost")=="Y" && mysql_result($result,$i,"take_turns")=="Y") {
                echo "Split Cost / Take Turns"; 
              }elseif (mysql_result($result,$i,"split_cost")=="Y" && mysql_result($result,$i,"take_turns")=="N") {
                echo "Split Cost"; 
              }elseif (mysql_result($result,$i,"split_cost")=="N" && mysql_result($result,$i,"take_turns")=="Y") {
                echo "Take Turns";
              }  
           ?>
          </p>
          
          <h4> 
          <?php if(mysql_result($result,$i,"mon")=="Y" or mysql_result($result,$i,"tue")=="Y" or mysql_result($result,$i,"wed")=="Y" or mysql_result($result,$i,"thu")=="Y" or mysql_result($result,$i,"fri")=="Y" or mysql_result($result,$i,"sat")=="Y" or mysql_result($result,$i,"sun")=="Y"){echo "Available Days:";} ?>
            <?php if(mysql_result($result,$i,"mon")=="Y"){echo "MON";} ?>   
            <?php if(mysql_result($result,$i,"tue")=="Y"){echo "TUE";} ?> 
            <?php if(mysql_result($result,$i,"wed")=="Y"){echo "WED";} ?> 
            <?php if(mysql_result($result,$i,"thu")=="Y"){echo "THU";} ?> 
            <?php if(mysql_result($result,$i,"fri")=="Y"){echo "FRI";} ?> 
            <?php if(mysql_result($result,$i,"sat")=="Y"){echo "SAT";} ?> 
            <?php if(mysql_result($result,$i,"sun")=="Y"){echo "SUN";} ?> 
          </h4>
          <?php 
              if (mysql_result($result,$i,"daily")=="Y") {
                echo "- Daily -"; 
              }
			  if (mysql_result($result,$i,"weekly")=="Y") {
                echo "- Weekly -"; 
              }
			  if (mysql_result($result,$i,"monthly")=="Y") {
                echo "- Monthly -";
              }  
           ?>
          <h4><?php echo "DEP :".mysql_result($result,$i,"origin_time") ?> - <?php echo "RET :".mysql_result($result,$i,"dest_time") ?></h4>
        </div>
        <div class="cus_row" style="width:15%; text-align: right;"> <img advId="<?php echo mysql_result($result,$i,"advert_id"); ?>" class="like-btn img-responsive" src="resources/icons/ilike_icon.png"  style="min-width: 40px;"/> </div>
      </div>
    </div>
  </div>

  <?php
  }
  ?>

  <br />

  <!-- Notification Panel -->
  <div id="includedNotifPanel"></div>
  
  <!-- Route Map Panel -->
  <div id="div-map-panel" style="position:fixed; top:17%; width:75%; height:72%; background-color: lightblue; border-style:double; left:15%;">
  	<?php include("showRoute_panel.php"); ?>
  </div>
  
  
  
  <div style="height:30px"></div>
  <!-- Site footer -->
  <div class="navbar navbar-inverse navbar-fixed-bottom">
    <div class="navbar-inner"> <a class="brand" href="#" style="padding-left:7%">&copy; Carpooling.lk 2013</a> </div>
  </div>
</div>
<div id="loading">
  <img id="img-load" src="resources/icons/loadera64.gif" /> 
</div>
<!-- /container -->

<!-- JAVASCRIPT INCLUDES -->
<!--<script type="text/javascript" src="Resources fro collapsible menu/bootstrap/js/bootstrap.min.js"></script>-->
<script type="text/javascript" src="resources/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-modal.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-transition.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-collapse.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-typeahead.js"></script>
<script type="text/javascript" src="resources/js/jquery.timepicker.js"></script>
<script type="text/javascript" src="common/admin.js"></script>
<script type="text/javascript">
		
	//Include Notification panel
	$(function(){
			   
	  var strRoute = "";
	  
      $("#includedNotifPanel").load("notification_panel.php"); 
	  
	  //Include Show Route panel
	  $("#div-map-panel").hide();

      $t = $("body"); // CHANGE it to the table's id you have
      $("#loading").css({
        opacity : 0.5,
        top     : $t.offset().top,
        width   : $t.outerWidth(),
        height  : $t.outerHeight()
      });
      
      $("#img-load").css({
        top  : ($t.height() / 2),
        left : ($t.width() / 2)
      });

      $('#srch_time').timepicker();
      $('.datepicker').datepicker();

      $("#loading").ajaxStart(function(){
        $(this).show();
      });

      $("#loading").ajaxStop(function(){
        $(this).hide();
      });
  });

	//Include Search panel
	$(function(){
    $("#includedSrchPanel").load("search_panel.php"); 
  });

  function submitForm(id, seat){
	//console.log("Desired Route Before Submitting : " + tempRoute);
    $("#loading").show();
      jQuery.ajax({
        url: 'saveReservation.php?advert_id=' + id + '&seat=' + seat +'&email=<?php echo $_SESSION['user_email']?>&desiredRoute=' + tempRoute,
        type: "GET",
        //data: $('#itemEditForm').serialize(),
        success: function(data) {
          if(data=="success"){
            //scrollToTop();
            alert("Your reservation is successful.");
  		updateNotifications(id, 'reserved');
          } else {alert("Something went wrong. Please try again.");}
        }
      });
      $("#loading").hide();
    }

    $(".accept-btn").bind('click', function(event){
      event.preventDefault();
      var id    = $(this).attr('id');
      var seat  = $(this).attr('rel');
      submitForm(id, seat);
    });
	
	$(".like-btn").bind('click', function(){
		var advertID = $(this).attr('advId');
		updateNotifications(advertID, 'liked');						  
    });
	
	function updateNotifications(advertID, action){
    $("#loading").show();
		jQuery.ajax({
			url: 'saveNotifications.php?advert_id=' + advertID +'&userID=<?php echo $_SESSION['user_email']?>&action=' + action,
			type: "GET",
			success: function(data) {
			  if(data=="success"){
				alert("Action successful and notified.");
			  }else if (data=="liked_once"){  
				alert("You already liked this post once.."); 
			  } else {alert("Something went wrong. Please try again.");}
			}
		});
    $("#loading").hide();
	}
    
  $(".user-button").bind('click', function(){
    var usrID = $(this).attr('usrID');
    document.location.href = "user_view.php?user_id=" + usrID;
  });
  
  $(".route-button").bind('click', function(){
	strRoute = "";
	tempRoute = "";
	
	strRoute = $(this).attr('strRoute');
	console.info(strRoute);
	$("#div-load-route").hide();
	$("#div-map-panel").show();
	initialize();
    loadSavedRoute(strRoute);
  });

</script>
</body>
</html>